<?php
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//
namespace AuctionCore\AuctionOrder;

use AuctionCore\System\AuctionException;
use AuctionCore\Common\Util;

/**
 * 拍单功能类
 * @author   Administrator
 */
class AuOrder
{

    protected $order_id = null;

    /**
     * 构造
     * @param    int $order_id 拍单编号 或 拍单id
     * @return   void
     */
    public function __construct($order_no_or_id)
    {
        if (is_numeric($order_no_or_id)) {
            $this->order_id = $order_no_or_id;
        } else {
            $r = M('order')->field('order_id')->where("order_no='{$order_no_or_id}'")->find();
            if ($r && count($r) > 0) {
                $this->order_id = $r['order_id'];
            } else {
                AuctionException::make_throw('700002');
            }
        }
    }

    /**
     * 拍单详情，以及拍单状态等。
     * @return   Array
     */
    public function detail()
    {
        return M('order')->where("order_id='{$this->order_id}'")->find();
    }


    /**
     * 基价不一致时输出最新信息到客户端
     * @param $dealer_id 车商ID
     */
    public function thorw_to_app($dealer_id,$code='700025'){
            $bidding_info = $this->get_bidding_info();
            $bidding_info['dealer_id'] = $dealer_id;
            //交易服务费
            $bidding_info['commision'] = get_commision($bidding_info['bidding_best_price']>0? $bidding_info['bidding_best_price']:$bidding_info['bid_start_price']);
            $msg = AuctionException::$codes[$code];
            echo Util::auto_jsonp_or_json($_REQUEST,array('msg'=>$msg,'code'=>$code,'data'=>$bidding_info));
            exit;
    }
    /**
     * 获得出价信息
     */
    public function get_bidding_info()
    {
        $order_id = $this->order_id;
        $m = M();
        $sql = "SELECT o.order_id,o.order_no,o.bid_start_price,o.bid_best_price,o.bidding_best_price,o.bid_best_dealer_id,o.transfer_fee,o.act_elapsed_time,o.est_elapsed_time,o.bidding_start_time,os.starttime
        ,o.bidding_best_dealer_id,IF(o.bidding_best_price=0,o.bid_start_price,o.bidding_best_price) as price
        ,UNIX_TIMESTAMP(o.bidding_start_time)+IF(o.act_elapsed_time>o.est_elapsed_time,o.act_elapsed_time,o.est_elapsed_time) - UNIX_TIMESTAMP(NOW()) AS left_time
        FROM au_order o INNER join au_order_scene os on os.scene_id = o.scene_id WHERE o.order_id='{$order_id}';";
        $r1 = $m->query($sql);
        if ($r1[0]['left_time'] <= 0)
            $r1[0]['left_time'] = 0;
        $sql = "SELECT COUNT(*) AS bidding_num,COUNT(DISTINCT dealer_id ) AS dealer_num  FROM au_bidding_log WHERE order_id='{$order_id}';";
        $r2 = $m->query($sql);
        $bidding_info = (array_merge($r1[0], $r2[0]));
        $bidding_info['starttime'] = intval(strtotime($bidding_info['starttime']))*1000;
        $bidding_info['bidding_start_time'] = intval(strtotime($bidding_info['bidding_start_time']))*1000;
        $bidding_info['act_elapsed_time'] = intval($bidding_info['act_elapsed_time'])*1000;
        $bidding_info['est_elapsed_time'] = intval($bidding_info['est_elapsed_time'])*1000;
        return $bidding_info;
    }


    /**
     * 更新拍单
     * @param array $info 要更新的拍单信息
     * @param array $map 条件
     * @return boolean
     */
    public function update($info, $map = array())
    {
        if (empty($map)) {
            $map['order_id'] = array('eq', $this->order_id);
        }
        $info['last_time'] = date('Y-m-d H:i:s');
        return M('order')->where($map)->save($info);
    }

    /*
     * 拍单参与竞拍车商统计
     * */
    public function stat_bidding_dealer()
    {
        return M('bidding_log')->where("order_id='" . $this->order_id . "'")->getField('count(distinct(dealer_id))');
    }

    /*
     * 拍单参与竞拍车商出价统计
     * */
    public function stat_bidding_price()
    {
        return M('bidding_log')->where("order_id='" . $this->order_id . "'")->count();
    }

    /*
     * 获取拍单出价记录
     * */
    public function get_bidding_price_log()
    {
        return M('bidding_log')->where("order_id='" . $this->order_id . "'")->order("bidding_id desc")->select();
    }


    /*
     * 根据order_id 获取car_id,owner_id
     * @return Array
     * */
    public function get_car_owner_id()
    {
        return M('order')->alias('o')->field("c.car_id,c.owner_id")->join(C('DB_PREFIX') . "cars c ON c.car_id=o.car_id")
            ->where("o.order_id='" . $this->order_id . "'")->find();
    }

    /*
     * 获取下一个拍品
     * @param int $scene_id 场次ID
     * @return Array
     * */
    public function get_next()
    {
        $order = $this->detail();
        $cond = "o.scene_id='" . $order['scene_id'] . "' AND bidding_start_time>'" . $order['bidding_start_time'] . "'";//301 为拍单状态 等待竞标
        $res = M('order')->alias('o')->field("o.order_id,o.order_no,o.status,c.car_cc,c.turbo,c.gearbox,c.brand_id,c.series_id,c.model_id")
            ->join(C('DB_PREFIX') . "cars c ON o.car_id=c.car_id")
            ->order("bidding_start_time")
            ->where($cond)->find();
        return $res;
    }


    /*
     * 出价(投标出价/竞价出价)
     * @param $tbl
     * @param $column
     * @return Array
     * */
    public function get_all_price()
    {
        $sql = "SELECT * FROM (
                SELECT * FROM
                (
                    SELECT `order_id`,`dealer_id`,`price`,`createtime` ,'bid' bidtype FROM au_bid_log a INNER JOIN (SELECT MAX(bid_id) bid_id FROM au_bid_log WHERE order_id='".$this->order_id."' GROUP BY dealer_id) b ON a.`bid_id` = b.bid_id
                    UNION
                    SELECT  `order_id`,`dealer_id`,`after_price` `price`,`createtime`,'bidding' bidtype FROM `au_bidding_log` WHERE `order_id` IN (SELECT `order_id` FROM `au_order` WHERE order_id='".$this->order_id."')
                 ) a ORDER BY order_id,price DESC,createtime DESC
        ) b GROUP BY order_id,dealer_id ORDER BY order_id,price DESC LIMIT 0,20";
        $arr = M()->query($sql);
        return array_slice($arr, 0, 20);
    }




    /**
     * 根据车源ID，查询拍单信息
     * */
    public static function get_order_by_car_id($car_id) {
        return M('order')->where("car_id='" . $car_id . "'")->order("order_id DESC")->find();
    }


    /**
     * 获取指定车源与车主签过约的拍单（跟拍单结果无关）
     * @param $car_id
     * @return mixed
     */
    public static  function get_signed_order($car_id){
        return M('order')->where("car_id='".$car_id."' AND status>=8")->order("order_id DESC")->select();
    }

    /**
     * 获取争议详情
     * @param $issue_id 争议ID
     */
    public function get_issue_detail($issue_id){
        return M('dealer_issue')->find($issue_id);
    }
    /**
     * 获取争议详情
     * @param $issue_id 争议ID
     */
    public static  function get_order_id_by_issue_id($issue_id){
        return M('dealer_issue')->where("issue_id='".$issue_id."'")->getField('order_id');
    }

    /**
    *修改
    **/
    public function updateOrder($data){
        $map = array();
        $map['order_id'] = array('eq',$this->order_id);
        return M('order')->where($map)->save($data);
    }

    /**
    * 生成一条贷款记录
    **/
    public function insert_loan_log($data){
        return M('loan_log')->add($data);
    }

    /**
    * 取消贷款时间
    **/
    public function cancel_loan(){
        $map = array();
        $map['order_id'] = $this->order_id;
        $data = array();
        $data['canceltime'] = date('Y-m-d H:i:s');
        return M('loan_log')->where($map)->save($data);
    }

    /**
    * 获取对应贷款编号的信息
    **/
    public static function get_loan_log($loanSN){
        $where = array();
        $where['xm_list_code'] = array('eq',$loanSN);
        return M('loan_log')->where($where)->find();
    }
    /**
    * order_id找到对应贷款信息
    **/
    public static function get_loan_log_by_order_id($order_id){
        $map = array();
        $map['order_id'] = array('eq',$order_id);
        return M('loan_log')->where($map)->find();
    }

    /**
     * 新增车商验车
     * 拍单ID,车商ID,创建时间
     * @return mixed
     */
    public function add_car_dealer_check()
    {
        /*添加车商验车记录*/
        $data = [];
        $data['order_id'] = $this->order_id;
        $dealer = $this->get_dealer_info();
        $data['dealer_id'] = $dealer['dealer_id'];
        $data['createtime'] = date("Y-m-d H:i:s");
        $data['check_limit_time'] = date("Y-m-d H:i:s", strtotime("+1 day"));
        $resCarDealerCheck = M('car_dealer_check')->add($data);
        /*回填拍单表验车状态*/
        $o = new  AuOrder($this->order_id);
        $resOrder = $o->update(array('check_car_status' => 1)); // 待验车
        if ($resCarDealerCheck !== false && $resOrder !== false) {
            return true;
        } else {
            return false;
        }
    }

     /**
     * 获取成交车商信息
     */
    public function get_dealer_info()
    {
        $cols = "d.*,o.order_id";
        $prefix = C('DB_PREFIX');
        $map = [];
        $map['o.order_id'] = $this->order_id;
        $map['da.status'] = 0;
        $info = M('order')->alias('o')->field($cols)
            ->join($prefix . "dealer_auctioned as da ON da.order_id=o.order_id")
            ->join($prefix . "car_dealer as d ON d.dealer_id=da.dealer_id")
            ->where($map)->find();
        return $info;
    }
    /**
     * 根据拍单ID找对应采购单信息
     *@return array
     */
    public function getPurchaseByOrderId(){
        $map = [];
        $map['o.order_id'] = $this->order_id;
        $purchaseInfo = M('order')->alias('o')->field('po.*')
            ->join(C('DB_PREFIX') . "cars as c ON o.`car_id` = c.`car_id`")
            ->join(C('DB_PREFIX') . "purchase_order as po ON po.`sid` = c.`sid`")
            ->where($map)->find();
        return $purchaseInfo;
    }
    /**
     * 根据拍单Id，锁定拍单
     * @return bool
     */
    public function lockByOrderId(){
        $arr = $this->detail();
        if($arr['is_lock'] == '1'){
            return false;
        }
        return M('order')->where(['order_id'=>$this->order_id])->save(['is_lock'=>1]);
    }

    /**
     * 根据拍单ID找对应状态收款信息
     * @return mixed
     */
    public function getCollectionIdByOid(){
        $data=[];
        $data['payment_type'] = ['in',[1,2,3]];
        $data['order_id'] = $this->order_id;
        $order_collection = M('order_collections')->where($data)->find();
        return $order_collection['collection_id'];
    }
    /**
     * 根据collectionID找对应收款信息
     * @param   $data
     * @return   $amount
     */
    public function getCaramount($collection_id){
        $map['id'] = array('eq',$collection_id);
        $amount = M('collection')->where($map)->find();
        return $amount['amount'];
    }
    /**
     * 根据mid找对应赔付信息
     * @param   $data
     * @return   $amount
     */
    public function getCarPayment($mid,$type){
        $map['ml.mid'] = array('eq',$mid);
        $map['pm.pay_type'] = array('eq',$type);
        $payment = M('modify_list')->alias('ml')
            ->join(C('DB_PREFIX')."change_payment as cp ON ml.mid = cp.change_id")
            ->join(C('DB_PREFIX')."payment as pm ON pm.id = cp.payment_id")
            ->where($map)->find();
        return $payment['amount'];
    }
    /**
     * 根据mid找对应收款信息
     * @param   $data
     * @return   $amount
     */
    public function getCarCollection($mid,$type){
        $map['ml.mid'] = array('eq',$mid);
        $map['co.payment_type'] = array('eq',$type);
        $payment = M('modify_list')->alias('ml')
            ->join(C('DB_PREFIX')."change_collection as cc ON ml.mid = cc.change_id")
            ->join(C('DB_PREFIX')."collection as co ON co.id = cc.collection_id")
            ->where($map)->find();
        return $payment['amount'];
    }
    /**
     *  结算时添加收款单信息
     * @param   $data
     * @return
     */
    public function set_collection($data){
        $res = M('collection')->add($data);
        return $res;
    }
    public static function  is_valid_order_no($order_no){
        return M('order')->where(array("order_no"=>$order_no))->find();
    }


}

//end class
